package com.cgtong.android.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.signature.ObjectKey;
import com.cgtong.android.R;
import com.cgtong.android.base.BaseTitleActivity;
import com.cgtong.android.http.ApiManager;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.mvp.contract.RegisterContract;
import com.cgtong.android.mvp.presenter.RegisterPresenter;
import com.cgtong.android.util.CommonUtils;
import com.cgtong.android.util.MD5Utils;
import com.cgtong.android.util.NoUnderLineSpan;
import com.cgtong.android.util.PostUtil;
import com.cgtong.android.widget.GlideApp;
import com.cgtong.android.widget.ValidCodeTime;
import com.kingja.loadsir.callback.SuccessCallback;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.DownloadProgressCallBack;
import com.zhouyou.http.exception.ApiException;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Sky.Bing on 2017/10/20.
 */

public class RegisterActivity extends BaseTitleActivity implements RegisterContract.View {
    @BindView(R.id.et_phone)
    public EditText mEtPhone;
    @BindView(R.id.et_validcode)
    public EditText mEtValidCode;
    @BindView(R.id.btn_getvalidcode)
    public Button mBtnGetValidCode;
    @BindView(R.id.et_login_password)
    public EditText mEtLoginPassword;
    @BindView(R.id.et_login_password_again)
    public EditText mEtLoginPasswordAgain;
    @BindView(R.id.chkbox_register_license)
    public CheckBox mChkRegisterLicense;
    @BindView(R.id.btn_register)
    public Button mBtnRegister;
    @BindView(R.id.tv_register_license)
    public TextView mTvRegisterLicense;
    @BindView(R.id.et_img_validcode)
    EditText mEtImgValidcode;
    @BindView(R.id.img_validcode)
    ImageView mImgValidcode;
    @BindView(R.id.loading_progress)
    ProgressBar mLoadingProgress;
    private RegisterPresenter mRegisterPresenter;

    private ValidCodeTime timeCount;
    private ProgressDialog progressDialog;
    private boolean isNeedLogin = true;
    public static final String REGISTER_PAGE_ID = "register";
    private int mPrevoiusPageIndex;
    public static final String EXTRA_REGISTERED_SHOW_PAGE = "show_page";

    @Override
    protected String getContentTitle() {
        return getResources().getString(R.string.txt_btn_register);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    protected void loadDataByNet() {
        timeCount = new ValidCodeTime(60000, 1000);
        timeCount.setTimeSetBtn(mBtnGetValidCode);
        mRegisterPresenter = new RegisterPresenter(this);
        SpannableString spannableString = new SpannableString(getResources().getString(R.string.txt_register_license));
        spannableString.setSpan(new NoUnderLineSpan() {
            @Override
            public void onClick(View widget) {
                Intent intent = new Intent(RegisterActivity.this, RegisterLicenseActivity.class);
                RegisterActivity.this.startActivity(intent);
            }
        }, 5, 18, Spanned.SPAN_MARK_MARK);
        mTvRegisterLicense.setText(spannableString);
        mTvRegisterLicense.setMovementMethod(LinkMovementMethod.getInstance());
        mChkRegisterLicense.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mBtnRegister.setEnabled(true);
                } else {
                    mBtnRegister.setEnabled(false);
                }
            }
        });
        if (null != getIntent()) {
            mPrevoiusPageIndex = getIntent().getIntExtra(EXTRA_REGISTERED_SHOW_PAGE, 0);
        }
        PostUtil.postCallbackDelayed(loadService, SuccessCallback.class);
        getImgValidCode();
    }

    @Override
    protected void backClick() {
        if (mPrevoiusPageIndex == ConstantManager.MAIN_PAGE_INDEX) {
            Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
            startActivity(intent);
        }
        super.backClick();
    }

    @Override
    public void onBackPressed() {
        backClick();
        super.onBackPressed();
    }

    @Override
    public void breakClickValidCode() {
        timeCount.start();
        ToastUtils.showLong(R.string.txt_success_send_valid_code);
    }

    /**
     * 获取图形验证码
     */
    @OnClick(R.id.img_validcode)
    public void getImgValidCode() {
        File imgDir = new File(ConstantManager.PHOTO_SAVE_DIR);
        EasyHttp.downLoad(ApiManager.URL_IMG_VALID)
                .savePath(imgDir.getAbsolutePath())
                .saveName("valid_code.png")
                .execute(new DownloadProgressCallBack<String>() {
                    @Override
                    public void update(long bytesRead, long contentLength, boolean done) {

                    }

                    @Override
                    public void onStart() {
                        //开始下载
                        mImgValidcode.setEnabled(false);
                        mLoadingProgress.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onComplete(String path) {
                        mImgValidcode.setEnabled(true);
                        //下载完成，path：下载文件保存的完整路径
                        GlideApp.with(RegisterActivity.this).load(path)
                                .skipMemoryCache(true)
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                .signature(new ObjectKey(System.currentTimeMillis()))
                                .into(mImgValidcode);
                        mLoadingProgress.setVisibility(View.GONE);

                    }

                    @Override
                    public void onError(ApiException e) {
                        mImgValidcode.setEnabled(true);
                        mLoadingProgress.setVisibility(View.GONE);
                        //下载失败
                        ToastUtils.showLong(R.string.txt_get_img_validcode_error);

                    }
                });

                }

        @OnClick(R.id.btn_getvalidcode)
        public void getValidCode () {
            String phone = mEtPhone.getText().toString();
            if (TextUtils.isEmpty(phone)) {
                ToastUtils.showLong(R.string.txt_empty_phone);
                return;
            }
            if (!RegexUtils.isMobileSimple(phone)) {
                ToastUtils.showLong(R.string.txt_phone_format_error);
                return;
            }
            String imgValidCode = mEtImgValidcode.getText().toString();
            if (TextUtils.isEmpty(imgValidCode)) {
                ToastUtils.showLong(R.string.txt_empty_img_validcode);
                return;
            }
            mRegisterPresenter.sendValidCode(phone, imgValidCode);
        }


        @OnClick(R.id.btn_register)
        public void doRegister () {
            String phone = mEtPhone.getText().toString();
            if (TextUtils.isEmpty(phone)) {
                ToastUtils.showLong(R.string.txt_empty_phone);
                return;
            }
            if (!RegexUtils.isMobileSimple(phone)) {
                ToastUtils.showLong(R.string.txt_phone_format_error);
                return;
            }
            String validCode = mEtValidCode.getText().toString();
            if (TextUtils.isEmpty(validCode)) {
                ToastUtils.showLong(R.string.txt_empty_validcode);
                return;
            }
            String password = mEtLoginPassword.getText().toString();
            if (TextUtils.isEmpty(password)) {
                ToastUtils.showLong(R.string.txt_empty_password);
                return;
            }
            if (CommonUtils.containsEmoji(password)) {
                ToastUtils.showLong(R.string.txt_password_nocontains_emoji);
                return;
            }
            if (!CommonUtils.checkPasswordRule(password)) {
                ToastUtils.showLong(R.string.txt_irregular_password);
                return;
            }
            String passwordAgain = mEtLoginPasswordAgain.getText().toString();
            if (TextUtils.isEmpty(passwordAgain)) {
                ToastUtils.showLong(R.string.txt_empty_password_again);
                return;
            }
            if (!password.equals(passwordAgain)) {
                ToastUtils.showLong(R.string.txt_diff_two_password);
                return;
            }
            if (isNeedLogin) {
                showProgressDialog();
            }
            mRegisterPresenter.doRegister(phone, CommonUtils.getMobileInfo(this), validCode, password, passwordAgain);
        }

        @Override
        protected void onDataReloadByNet (View v){
        }

        @Override
        public void onRegisterError (ApiException e){
            if (!TextUtils.isEmpty(e.getMessage())) {
                ToastUtils.showLong(e.getMessage());
            } else {
                ToastUtils.showLong(R.string.txt_regsiter_error);
            }
        }

        @Override
        public void onRegisterSuccess () {
            if (isNeedLogin) {
                String phone = mEtPhone.getText().toString();
                String password = mEtLoginPassword.getText().toString();
                mRegisterPresenter.doLogin(phone, MD5Utils.md5(password), CommonUtils.getMobileInfo(this));
            } else {
                ToastUtils.showLong(R.string.txt_register_success);
                finish();
            }
        }

        @Override
        public void sendValidCodeError (ApiException e){
            if (!TextUtils.isEmpty(e.getMessage())) {
                ToastUtils.showLong(e.getMessage());
            } else {
                ToastUtils.showLong(R.string.txt_sendvalidcode_error);
            }
        }

    private void showProgressDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("注册中...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setIndeterminate(false);
        progressDialog.show();
    }

    private void dismissProgressDialog() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void onLoginSuccess() {
        dismissProgressDialog();
        ToastUtils.showLong(R.string.txt_register_success);
        Intent intent = new Intent(RegisterActivity.this, MyInfoActivity.class);
        intent.putExtra("from", REGISTER_PAGE_ID);
        RegisterActivity.this.startActivity(intent);
        finish();
    }

    @Override
    public void onLoginError() {
        dismissProgressDialog();
        ToastUtils.showLong(R.string.txt_register_success);
        finish();
    }

}